package com.sofn.rest.config;

import com.sofn.rest.dao.UserDao;
import com.sofn.rest.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;

/**
 * Authors: sofn
 * Version: 1.0  Created at 2015-11-04 21:40.
 */
@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws
            UsernameNotFoundException {
        User user = this.userDao.findByName(username);
        if (user == null) {
            throw new UsernameNotFoundException("Username " + username + " not found");
        }
        return new org.springframework.security.core.userdetails.User(username, "password", getGrantedAuthorities(username));
    }

    private Collection<? extends GrantedAuthority> getGrantedAuthorities(String username) {
        Collection<? extends GrantedAuthority> authorities;
        if (username.equals("John")) {
            authorities = Arrays.asList(() -> "ROLE_ADMIN", () -> "ROLE_BASIC");
        } else {
            authorities = Arrays.asList(() -> "ROLE_BASIC");
        }
        return authorities;
    }
}
